import aliOSS from 'ali-oss'
import type { MultipartUploadOptions } from 'ali-oss'
import { getSTSTokenApi } from '@/api/alioss'
import OSS from 'ali-oss'

export class OSSUtil {
  private static client: aliOSS | null = null
  private static readonly region: string = 'oss-cn-hangzhou'
  private static readonly endpoint = 'oss.chenmignxu.cn'

  private constructor() {}

  // 初始化
  static async init(bucket: string) {
    const { accessKeyId, accessKeySecret, stsToken } = await OSSUtil.getSTSToken()

    if (!OSSUtil.client) {
      OSSUtil.client = new OSS({
        region: OSSUtil.region,
        // @ts-ignore
        authorizationV4: true,
        accessKeyId,
        accessKeySecret,
        stsToken,
        bucket,
        endpoint: OSSUtil.endpoint,
        cname: true,
        refreshSTSToken: OSSUtil.getSTSToken,
        refreshSTSTokenInterval: 50 * 60 * 1000 // 50分钟
      })
    }
  }

  // 获取STS Token
  private static async getSTSToken() {
    const result = await getSTSTokenApi()
    const { accessKeyId, accessKeySecret, securityToken } = result.content
    return {
      accessKeyId,
      accessKeySecret,
      stsToken: securityToken
    }
  }

  // 检查是否已经初始化
  private static checkIsInit() {
    if (!OSSUtil.client) {
      throw new Error('请先执行init方法初始化')
    }
  }

  // 分片上传
  public static async multipartUpload(name: string, file: Blob, options: MultipartUploadOptions) {
    OSSUtil.checkIsInit()
    const client = OSSUtil.client!
    const res = await client.multipartUpload(name, file, options)
    return res
  }

  // 获取临时预览地址
  public static signatureUrl(name: string): string {
    OSSUtil.checkIsInit()
    const client = OSSUtil.client!
    return client.signatureUrl(name)
  }
}
